package DB;
import Model.*;
import java.sql.*;

import Model.Customer;

/**
 *
 * @author Selemani
 */

public class CustomerManager implements IFCustomerManager{

     private  Connection con;
     private StatusManager statusManager;
    /** Creates a new instance
     * of CustomerManager */
    public CustomerManager() {
      con = DBConnector.getInstance().getDBConnection();
      statusManager = new StatusManager();
    }

    public Customer getCustomer(int customerId, boolean retrieveAssociations) throws IllegalArgumentException {
        String param = ""+customerId;
        return singleWhere("customerId = ?",new String[]{param},retrieveAssociations);
    }
 private Customer singleWhere(String whereC, String[] params, boolean assoc){
        ResultSet results;
        Customer customer = null;

        String query = buildQuery(whereC);
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            for(int a = 0; a<params.length;a++){
              stmt.setString(a+1, params[a]);
            }
            stmt.setQueryTimeout(5);
            results = stmt.executeQuery();
            if(results.next()){
                customer = buildCustomer(results);
                stmt.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        if(customer == null){
            throw new IllegalArgumentException("Customer not found");
        }
        return customer;
    }
    private String buildQuery(String whereC){
        String query = "SELECT * FROM Customer";
        if(!whereC.isEmpty()){
            query = query+" WHERE "+whereC;
        }
        return query;
    }
    private Customer buildCustomer(ResultSet resSet){
        Customer customer = new Customer();
        try {
            customer.setCustomerId(resSet.getInt(1));
            customer.setName(resSet.getString(2));
            customer.setAddress(resSet.getString(3));
            customer.setPhoneNo(resSet.getString(4));
            customer.setZipCode(new ZipCode("DK 9000","Aalborg"));
            customer.setType(new Type(1,"Private"));
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return customer;
    }
}